<template>
  <div class="ele-body">
    <!-- 搜索表单 -->
    <div class="block-interval">
      <a-card :bordered="false">
        <a-form layout="inline" :model="where">
          <a-row>
            <a-form-item label="所属牛能牧场:" name="ranchId">
              <a-select
                show-search
                v-model:value="where.ranchId"
                placeholder="请选择所属牛能牧场"
                style="width: 205px;"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                allow-clear
              >
                <a-select-option v-for="item in ranchList" :key="item.ranchId" >
                  {{ item.ranchName }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item label="所属牧云汇牧场:" name="farmId">
              <a-select
                show-search
                v-model:value="where.farmId"
                placeholder="请选择所属牧云汇牧场"
                style="width: 205px;"
                :show-arrow="false"
                :filter-option="false"
                :not-found-content="null"
                allow-clear
              >
                <a-select-option v-for="item in farmList" :key="item.farmId" >
                  {{ item.name }}
                </a-select-option>
              </a-select>
            </a-form-item>

            <a-form-item class="ele-text-center">
              <a-space>
                <a-button type="primary" @click="reload">查询</a-button>
                <a-button @click="reset">重置</a-button>
              </a-space>
            </a-form-item>
          </a-row>
        </a-form>
      </a-card>
    </div>

    <!-- 表格 -->
    <div>
      <a-card :bordered="false">
        <ele-pro-table
          ref="table"
          row-key="placeId"
          :datasource="datasource"
          :columns="columns"
          :where="where"
          :scroll="{ x: 'max-content' }"
        >
          <template #bodyCell="{ column, record }">

            <!-- 牛舍字段可编辑 -->
            <template v-if="column.dataIndex === 'oxtallName'">
              <div v-if="editingId === record.placeId && editingField === 'oxtallName'">
                <div style="display: flex; flex-direction: column;">
                  <a-select
                    v-model:value="editingOxtallId"
                    style="width: 120px; margin-bottom: 4px;"
                    placeholder="请选择牛舍"
                  >
                    <a-select-option v-for="item in tempOxtallList" :key="item.oxtallId">
                      {{ item.oxtallName }}
                    </a-select-option>
                  </a-select>
                  <div style="display: flex; justify-content: center;">
                    <a-button type="link" size="small" @click="saveOxtall(record)" style="padding: 0 8px;">
                      <check-outlined />
                    </a-button>
                    <a-button type="link" size="small" @click="cancelEdit" style="padding: 0 8px;">
                      <close-outlined />
                    </a-button>
                  </div>
                </div>
              </div>
              <div v-else>
                <a-space>
                  <span>{{ record.oxtallName }}</span>
                  <a-button type="link" size="small" @click="startEditOxtall(record)">
                    <edit-outlined />
                  </a-button>
                </a-space>
              </div>
            </template>

            <!-- table操作栏按钮 -->
            <template v-if="column.key === 'action'">
              <a-space>
                <a @click="openConfigModal(record)">关联配置</a>
                <a-divider type="vertical" />
                <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(record)">
                  <a class="ele-text-danger">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </template>
        </ele-pro-table>
      </a-card>
    </div>

    <!-- 关联配置弹窗 -->
    <a-modal
      v-model:visible="showConfigModal"
      title="关联配置"
      okText="变更确认"
      cancelText="取消变更"
      @ok="handleConfigOk"
      @cancel="handleConfigCancel"
      width="1200px"
    >
      <a-table
        :columns="configColumns"
        :data-source="configList"
        :row-selection="{
          type: 'radio',
          selectedRowKeys: selectedConfigKeys,
          onChange: onSelectChange
        }"
        :pagination="false"
        row-key="configId"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'placesInfo'">
            <div v-if="record.places && record.places.length > 0">
              <div v-for="place in record.places" :key="place.placeId">
                {{ place.placeName }}
                <span v-if="place.oxtallName">（关联牛能牛舍：{{ place.oxtallName }}）</span>
              </div>
            </div>
            <span v-else>无关联牛舍</span>
          </template>
          <template v-if="column.key === 'action'">
            <a-space>
              <a @click="editConfig(record)">编辑</a>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-modal>
    <DeviceManagerdeviceAiedgeComputerHazzxConfigEdit v-if="configEditShow" v-model:visible="configEditShow" :scene="'place'" :placeId="currentPlaceId" :data="configCurrent" @done="reloadConfig" />

  </div>
</template>

<script>
import { DeviceAiEdgeFarmApi } from '@/api/property/aiedgecomputer/DeviceAiEdgeFarmApi';
import { DeviceAiEdgePlaceApi } from '@/api/property/aiedgecomputer/DeviceAiEdgePlaceApi';
import { DeviceAiEdgeSprayConfigApi } from '@/api/property/aiedgecomputer/DeviceAiEdgeSprayConfigApi';
import { RanchApi } from '@/api/property/RanchApi';
import { OxtallApi } from '@/api/property/OxtallApi';
import { message } from 'ant-design-vue';
import DeviceManagerdeviceAiedgeComputerHazzxConfigEdit from './hazzxconfig-edit.vue'

export default {
  name: 'DeviceManagerdeviceAiedgeComputerHazzxPlaceList',
  components: {
    DeviceManagerdeviceAiedgeComputerHazzxConfigEdit,
  },
  async mounted() {
  },
  async created() {
    let that = this;
    RanchApi.list({}).then(resp => {
      let _ranchList = (resp ? resp.data : null) || [];
      that.ranchList = _ranchList;
    });

    DeviceAiEdgeFarmApi.list({}).then(resp => {
      let _farmList = (resp ? resp.data : null) || [];
      that.farmList = _farmList;
    });
  },
  data() {
    return {
      // 表格列配置
      columns: [
        {
            title: '牧云汇牛舍ID',
            dataIndex: 'placeId'
        },
        {
          title: '牧云汇牛舍名称',
          dataIndex: 'name'
        },
        {
          title: '所属牛能牧场名称',
          dataIndex: 'ranchName'
        },
        {
          title: '所属牧云汇牧场名称',
          dataIndex: 'farmName'
        },
        {
          title: '关联的牛能牛舍名称',
          dataIndex: 'oxtallName'
        },
        {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center',
        }
      ],
      // 表格搜索条件
      where: {},
      // 当前编辑数据
      current: null,
      // 是否显示编辑弹窗
      showEdit: false,
      ranchList : [],
      farmList : [],
      editingId: null,
      editingValue: null,
      // 添加新的编辑状态变量
      editingField: null,
      editingOxtallId: null,
      // 临时存储编辑时的选项列表
      tempOxtallList: [],

      // 配置相关数据
      showConfigModal: false,
      configList: [],
      selectedConfigKeys: [],
      currentRecord: null,
      configColumns: [
        {
          title: '配置ID',
          dataIndex: 'configId',
          width: 100
        },
        {
          title: '配置名称',
          dataIndex: 'configName'
        },
        {
          title: '关联牛舍',
          dataIndex: 'placesInfo',
          width: 500
        },
         {
          title: '操作',
          key: 'action',
          width: 150,
          align: 'center'
        }
      ],
      configCurrent : null,
      configEditShow : false
    };
  },
  methods: {
    /**
     * 搜索按钮
     *
     * @author cancan
     * @date 2025/06/28 19:48
     */
    reload() {
      this.selection = [];
      this.$refs.table.reload({ page: 1 });
    },

    /**
     * 重置搜索
     *
     * @author cancan
     * @date 2025/06/28 19:48
     */
    reset() {
      this.where.ranchId = '';
      this.where.farmId = '';
      this.$nextTick(() => {
        this.reload();
      });
    },

    /**
     * 删除
     *
     * @author cancan
     * @date 2025/06/28 19:48
     */
    async remove(row) {
      const result = await DeviceAiEdgePlaceApi.delete({ placeId: row.placeId });
      this.$message.success(result.message);
      this.reload();
    },

    /**
     * 打开新增或编辑弹窗
     *
     * @author cancan
     * @date 2025/06/28 19:48
     */
    openEdit(row) {
      this.current = row;
      this.showEdit = true;
    },
    datasource({ page, limit, where, orders }) {
      return DeviceAiEdgePlaceApi.findPage({ ...where, ...orders, pageNo: page, pageSize: limit });
    },

     /**
     * 开始编辑牛舍
     */
    async startEditOxtall(record) {
      if (!record.ranchId) {
        message.warning('请先完善牧场关联');
        return;
      }
      
      this.editingId = record.placeId;
      this.editingField = 'oxtallName';
      this.editingOxtallId = record.oxtallId == '0'? undefined : record.oxtallId;
      
      // 获取牛舍列表，基于当前记录的牧场ID
      try {
        const result = await OxtallApi.list({"orgId": record.ranchId});
        this.tempOxtallList = (result ? result.data : null) || [];
        if (this.tempOxtallList.length === 0) {
          message.warning('当前牧场下没有牛舍');
        }
      } catch (err) {
        console.log(err);
        message.error('获取牛舍列表失败' + (err.message || '未知错误'));
      }
    },

    /**
     * 保存牛舍
     */
    async saveOxtall(record) {
      try {
        const updateData = {
          placeId: record.placeId,
          oxtallId: this.editingOxtallId,
        };
        
        await DeviceAiEdgePlaceApi.edit(updateData);
        message.success('牛舍更新成功');
        
        // 更新当前记录的牛舍信息
        const selectedOxtall = this.tempOxtallList.find(item => item.oxtallId === this.editingOxtallId);
        if (selectedOxtall) {
          record.oxtallId = selectedOxtall.oxtallId;
          record.oxtallName = selectedOxtall.oxtallName;
        }
        
        this.cancelEdit();
      } catch (error) {
        message.error('牛舍更新失败' + (error.message || '未知错误'));
      }
    },

    /**
     * 取消编辑
     */
     cancelEdit() {
      this.editingId = null;
      this.editingValue = null;
      this.editingField = null;
      this.editingOxtallId = null;
    },


    /**
     * 打开配置弹窗
     */
    async openConfigModal(record) {
      this.currentRecord = record;
      this.showConfigModal = true;
      // 先重置选中状态
      this.selectedConfigKeys = [];
      
      try {
        // 获取配置列表
        const result = await DeviceAiEdgeSprayConfigApi.list({"farmId" : record.farmId, "getAllocation" : 1});
        this.configList = result.data || [];
        
        // 遍历配置列表，找到包含当前placeId的配置
        const selectedConfig = this.configList.find(config => 
          config.places?.some(place => place.placeId === record.placeId)
        );
        
        if (selectedConfig) {
          // 使用 nextTick 确保在 DOM 更新后设置选中状态
          this.$nextTick(() => {
            this.selectedConfigKeys = [selectedConfig.configId];
          });
        }
      } catch (error) {
        message.error('获取配置列表失败：' + (error.message || '未知错误'));
      }
    },
    
    /**
     * 选择配置变更
     */
    onSelectChange(selectedRowKeys) {
      this.selectedConfigKeys = selectedRowKeys;
    },
    
    /**
     * 确认关联配置
     */
    async handleConfigOk() {
      if (!this.currentRecord || this.selectedConfigKeys.length === 0) {
        message.warning('请选择要关联的配置');
        return;
      }
      
      try {
        // 找到当前牛舍关联的配置
        const oldConfig = this.configList.find(config => 
          config.places?.some(place => place.placeId === this.currentRecord.placeId)
        );
        await DeviceAiEdgeSprayConfigApi.huanBind({
          farmId : this.currentRecord.farmId,
          placeId: this.currentRecord.placeId,
          newConfigId: this.selectedConfigKeys[0],
          oldConfigId: oldConfig?.configId // 添加旧配置ID
        });
        message.loading('配置关联成功，正在同步中...', 5);
        this.showConfigModal = false;
        setTimeout(() => {
          this.reload(); // 延迟刷新列表
        }, 5000);
      } catch (error) {
        message.error('配置关联失败：' + (error.message || '未知错误'));
      }
    },
    
    /**
     * 取消关联配置
     */
    handleConfigCancel() {
      this.showConfigModal = false;
      this.$nextTick(() => {
        this.selectedConfigKeys = [];
        this.currentRecord = null;
        this.configList = [];
      });
    },
    /**
     * 编辑配置
     */
    editConfig(record) {
      this.configCurrent = record;
      this.currentPlaceId = this.currentRecord.placeId;
      this.configEditShow = true;
    },

    async reloadConfig() {
      // 先重置选中状态
      this.selectedConfigKeys = [];
      
      try {
        // 获取配置列表
        const result = await DeviceAiEdgeSprayConfigApi.list({"farmId" : this.currentRecord.farmId, "getAllocation" : 1});
        this.configList = result.data || [];
        
        // 遍历配置列表，找到包含当前placeId的配置
        const selectedConfig = this.configList.find(config => 
          config.places?.some(place => place.placeId === this.currentRecord.placeId)
        );
        
        if (selectedConfig) {
          // 使用 nextTick 确保在 DOM 更新后设置选中状态
          this.$nextTick(() => {
            this.selectedConfigKeys = [selectedConfig.configId];
          });
        }
      } catch (error) {
        message.error('获取配置列表失败：' + (error.message || '未知错误'));
      }
    }
  }
};
</script>